package com.qs.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qs.apigateway.constant.RedisConstant;
import com.qs.apigateway.utils.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @Desc:  权限拦截（区分买家和卖家）
 * @author: jianfeng
 * @Time: 2019/9/25 10:37
 */
@Component
public class AuthBuyerFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    /**
     * @Desc:  是否应该拦截
     * @author: jianfeng
     * @Time: 2019/9/26 11:10
     * @return boolean
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();

        //判断买家
        if ("/order/order/create".equals(request.getRequestURI())){
            return true;
        }

        //判断卖家
        if ("/order/order/finish".equals(request.getRequestURI())){
            return true;
        }

        return false;
    }

    /**
     * @Desc:  业务代码，每次请求的url都要带上token
     * @author: jianfeng
     * @Time: 2019/9/25 10:54
     * @return java.lang.Object
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();

        /**
         * /order/create  只能买家访问(cookie里有openid)
         * /order/finish  只能卖家访问（cookie里有token，并且对应的redis中有值）
         * /product/list  都可以访问
         */
        //判断买家

        Cookie cookie= CookieUtil.get(request,"openid");
        if (cookie==null||StringUtils.isEmpty(cookie.getValue())){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }



        return null;
    }
}
